import org.apache.poi.xwpf.usermodel.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartUtilities;

import java.io.File;
import java.io.IOException;

import org.apache.poi.util.IOUtils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class a{
    public static void main(String[] args) {
        // 创建一个数据集
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(12, "Sunny", "Monday");
        dataset.addValue(19, "Sunny", "Tuesday");
        dataset.addValue(4, "Snow", "Monday");
        dataset.addValue(2, "Snow", "Tuesday");

        // 创建一个条形图
        JFreeChart chart = ChartFactory.createBarChart(
                "Weekly Weather Conditions", // 图表标题
                "Day", // 域名
                "Temperature (C)", // 值域
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 条形图垂直显示
                true, // 显示图例
                true,
                false
        );

        // 设置图表的大小
        int width = 800;   // 图表宽度
        int height = 600;  // 图表高度

        // 将图表保存为PNG文件
        try {
            ChartUtilities.saveChartAsPNG(new File("weather_chart.png"), chart, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error saving the chart as a PNG file.");
        }


        //
        try {
            // 加载现有的Word文档
            XWPFDocument document = new XWPFDocument(new FileInputStream("input.docx"));

            // 创建一个新段落，用于插入图片
            XWPFParagraph paragraph = document.createParagraph();

            // 在段落中添加一个新运行，用于插入图片
            XWPFRun run = paragraph.createRun();

            // 读取图片文件
            InputStream inputStream = new FileInputStream("weather_chart.png");


            XWPFPicture picture = run.addPicture(inputStream, XWPFDocument.PICTURE_TYPE_PNG,"weather_chart.png", 4000000, 3000000);
            // 保存文档



            try (FileOutputStream out = new FileOutputStream("output.docx")) {
                document.write(out);
            }

            // 关闭文档和图片的输入流
            document.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}